<template>
  <div>
    <div ref="echarts" style="width: 600px; height: 400px;"></div>
    <button type="button" @click="testSocket">点击</button>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import io from 'socket.io-client';
export default {
  name: 'EChartsComponent',
  data () {
    return {
      myChart: undefined,
      socket: undefined,
    }
  },
  mounted () {
    this.showEcharts()
    this.initSocket()
  },
  methods: {
    showEcharts () {
      this.myChart = echarts.init(this.$refs.echarts)
      this.myChart.setOption({
        title: {
          text: '折线图'
        },
        tooltip: {},
        xAxis: {
          data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
        },
        yAxis: {},
        series: [
          {
            name: '储量',
            type: 'line',
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      })
    },
    initSocket () {
      this.socket = io('http://localhost:5000/test');
      // 监听连接
      this.socket.on('connect', () => {
        console.log('websock连接了');
      });
      // 监听断开
      this.socket.on('disconnect', () => {
        console.log('websocket 关闭了');
      });
      // 接收服务器发送给客户端的消息
      this.socket.on('my_response', (msg) => {
        const back = JSON.parse(msg)
        console.log(back)
        this.myChart.setOption({
          series: [
            {
              name: '储量',
              type: 'line',
              data: back.data
            }
          ]
        })
      });
    },
    testSocket () {
      // 发送消息到服务器
      this.socket.emit('my_event', { "name": "200" });
    }
  }
}
</script>
<style lang="scss" scoped></style>
